package com.liuhaozzu.hibernate.demo.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {

	private static final ThreadLocal<Session> THREAD_LOCAL=new ThreadLocal<>();
	private static Configuration cfg=null;
	private static SessionFactory factory=null;
	private static Session session=null;
	
	static {
		try {
			cfg=new Configuration().configure();
			factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
										.applySettings(cfg.getProperties()).build());
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Session getSession(){
		session=THREAD_LOCAL.get();
		if (session==null && !session.isOpen()) {
			if (factory==null) {
				factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
						.applySettings(cfg.getProperties()).build());
			}
			session=(factory!=null) ? factory.openSession():null;
			THREAD_LOCAL.set(session);
		}
		return session;
	}
	
	public static void closeSession(){
		if (session!=null && session.isOpen()) {
			session.close();
		}
	}
}
